
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import ValidationError
from asset.models import *
import os, json, time
from django.db.models import Q
from django.conf import settings
from django.http import FileResponse
import xlrd
from openpyxl import load_workbook
from io import BytesIO

from utils.custom_log   import log_start
logger = log_start('Excel')



class ExcelCreateHostView(APIView):
    # 下载excel模板
    def get(self, request):
        file_name = 'host.xlsx'
        logger.info(f"请求文件:{file_name}")
        try:
            file_path = os.path.join(settings.BASE_DIR, 'apps/asset', 'files', file_name)
            response = FileResponse(open(file_path, 'rb'))
            response['Content-Type'] = 'application/octet-stream'
            response['Content-Disposition'] = 'attachment; filename=%s' %file_name
            return response
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        
        

        

    # 导入表格
    def post(self, request):
        region_id = int(request.data.get('region')) # 区域id
        server_group_id_list = request.data.get('server_group') # 分组id
        connect_type = request.data.get('connect_type')  # 用户选择使用内网（private）还是公网（public），下面判断对应录入
        ssh_id = request.data.get('ssh_id')
        logger.info(f"{request.data}")


        file_in_memory = request.FILES['file'].read()
        # logger.info(f"打印上传文件: {file_in_memory}")
        # logger.info(f"打印上传: {request.data}")
        excel_file_obj = request.data['file']

        try:
            # data = xlrd.open_workbook(file_contents=excel_file_obj.read())
            workbook_object = load_workbook(filename=BytesIO(file_in_memory))
        except Exception as e:
            res = {'code': 10000, 'detail': f'请上传xls类型文件! {e}'}
            return Response(res)
        
        # table = data.sheets()[0]  # 打开第一个工作表
        # nrows = table.nrows  # 获取表的行数
        # row_data = data[1:]  # 获取表数据

        sheet_name = workbook_object.sheetnames[0]
        print(sheet_name)
        sheet_object = workbook_object[sheet_name]
        print(sheet_object)
        
        data = list(sheet_object.iter_rows(values_only=True))
        row_title = data[0]  # 获取表头
        row_data = data[1:]  # 获取表数据
        print("表头:",row_title)
        print("row_data:", row_data)
        

        ssh_instance = SSH_account.objects.get(id=ssh_id)
        region_instance = Region.objects.get(id=region_id)
        logger.error(f"{region_instance}")
        try:
            for row in row_data: # 循环行
                if row[0]:
                    hostname = row[0]  
                    ip=row[1]  if row[1] else ""
                    floatingip=row[2] if row[2] else ""
                    desc=row[3] if row[3] else ""
                    logger.info(f"{hostname}")
    
                    server = Host.objects.create(
                        hostname=hostname,
                        ip=ip,
                        floatingip=floatingip,
                        desc=desc,
                        ssh_id = ssh_instance,
                        region_id=region_instance,
                        connect_type=connect_type,
                 
                    )
                   # 添加多对多字段
                    for group_id in server_group_id_list:
                        group = Group.objects.get(id=group_id)  # 获取分组
                        server.group_id.add(group)  # 将服务器添加到分组
                res = {'code': 20000, 'detail': '导入成功'}
        except Exception as e:
            res = {'code': 10000, 'detail': '导入异常！%s' %e}

        return Response(res)
